package com.vehiclemanagement.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vehiclemanagement.common.CommonResult;
import com.vehiclemanagement.entity.TrafficViolation;
import com.vehiclemanagement.service.TrafficViolationService;
import com.vehiclemanagement.service.VehicleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 交通违章记录控制器
 */
@RestController
@RequestMapping("/traffic-violation")
public class TrafficViolationController {

    @Autowired
    private TrafficViolationService trafficViolationService;
    
    @Autowired
    private VehicleService vehicleService;

    /**
     * 分页查询交通违章记录
     */
    @GetMapping("/list")
    public CommonResult<IPage<TrafficViolation>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String searchTerm,
            @RequestParam(required = false) Long vehicleId,
            @RequestParam(required = false) Long driverId,
            @RequestParam(required = false) String violationType,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
        
        IPage<TrafficViolation> page = trafficViolationService.pageViolations(current, size, searchTerm, vehicleId, 
                driverId, violationType, status, startTime, endTime);
        
        return CommonResult.success(page);
    }

    /**
     * 根据ID获取交通违章记录详情
     */
    @GetMapping("/{id}")
    public CommonResult<TrafficViolation> getById(@PathVariable Long id) {
        TrafficViolation violation = trafficViolationService.getViolationById(id);
        if (violation == null) {
            return CommonResult.failed("违章记录不存在");
        }
        return CommonResult.success(violation);
    }

    /**
     * 添加交通违章记录
     */
    @PostMapping
    public CommonResult<Boolean> add(@RequestBody TrafficViolation violation) {
        // 参数验证
        if (violation.getVehicleId() == null) {
            return CommonResult.failed("车辆信息不能为空");
        }
        if (violation.getViolationTime() == null) {
            return CommonResult.failed("违章时间不能为空");
        }
        if (violation.getViolationType() == null || violation.getViolationType().trim().isEmpty()) {
            return CommonResult.failed("违章类型不能为空");
        }
        
        // 检查车辆是否存在
        if (!vehicleService.exists(violation.getVehicleId())) {
            return CommonResult.failed("车辆不存在");
        }
        
        // 添加违章记录
        boolean result = trafficViolationService.addViolation(violation);
        
        if (result) {
            return CommonResult.success(true, "添加违章记录成功");
        } else {
            return CommonResult.failed("添加违章记录失败");
        }
    }

    /**
     * 修改交通违章记录
     */
    @PutMapping
    public CommonResult<Boolean> update(@RequestBody TrafficViolation violation) {
        if (violation.getId() == null) {
            return CommonResult.failed("违章记录ID不能为空");
        }
        
        // 验证记录是否存在
        TrafficViolation existingViolation = trafficViolationService.getViolationById(violation.getId());
        if (existingViolation == null) {
            return CommonResult.failed("违章记录不存在");
        }
        
        boolean result = trafficViolationService.updateViolation(violation);
        
        if (result) {
            return CommonResult.success(true, "修改违章记录成功");
        } else {
            return CommonResult.failed("修改违章记录失败");
        }
    }

    /**
     * 删除交通违章记录
     */
    @DeleteMapping("/{id}")
    public CommonResult<Boolean> delete(@PathVariable Long id) {
        // 验证记录是否存在
        TrafficViolation existingViolation = trafficViolationService.getViolationById(id);
        if (existingViolation == null) {
            return CommonResult.failed("违章记录不存在");
        }
        
        boolean result = trafficViolationService.deleteViolation(id);
        
        if (result) {
            return CommonResult.success(true, "删除违章记录成功");
        } else {
            return CommonResult.failed("删除违章记录失败");
        }
    }

    /**
     * 处理交通违章
     */
    @PutMapping("/handle/{id}")
    public CommonResult<Boolean> handleViolation(
            @PathVariable Long id,
            @RequestParam String handler,
            @RequestParam String handlingMethod,
            @RequestParam(required = false) String remark) {
        
        // 验证违章记录是否存在
        TrafficViolation existingViolation = trafficViolationService.getViolationById(id);
        if (existingViolation == null) {
            return CommonResult.failed("违章记录不存在");
        }
        
        boolean result = trafficViolationService.handleViolation(id, handler, handlingMethod, remark);
        
        if (result) {
            return CommonResult.success(true, "处理违章记录成功");
        } else {
            return CommonResult.failed("处理违章记录失败");
        }
    }

    /**
     * 获取车辆累计罚款金额
     */
    @GetMapping("/sum-fine-amount/vehicle/{vehicleId}")
    public CommonResult<BigDecimal> sumFineAmountByVehicle(@PathVariable Long vehicleId) {
        // 验证车辆是否存在
        if (!vehicleService.exists(vehicleId)) {
            return CommonResult.failed("车辆不存在");
        }
        
        BigDecimal totalAmount = trafficViolationService.sumFineAmountByVehicleId(vehicleId);
        return CommonResult.success(totalAmount);
    }

    /**
     * 获取驾驶员累计罚款金额
     */
    @GetMapping("/sum-fine-amount/driver/{driverId}")
    public CommonResult<BigDecimal> sumFineAmountByDriver(@PathVariable Long driverId) {
        // 验证驾驶员是否存在
        // (假设有driverService.exists方法，实际使用时根据项目情况调整)
        // if (!driverService.exists(driverId)) {
        //     return CommonResult.failed("驾驶员不存在");
        // }
        
        BigDecimal totalAmount = trafficViolationService.sumFineAmountByDriverId(driverId);
        return CommonResult.success(totalAmount);
    }

    /**
     * 获取车辆累计扣分
     */
    @GetMapping("/sum-point-deduction/vehicle/{vehicleId}")
    public CommonResult<Integer> sumPointDeductionByVehicle(@PathVariable Long vehicleId) {
        // 验证车辆是否存在
        if (!vehicleService.exists(vehicleId)) {
            return CommonResult.failed("车辆不存在");
        }
        
        Integer totalPoints = trafficViolationService.sumPointDeductionByVehicleId(vehicleId);
        return CommonResult.success(totalPoints);
    }

    /**
     * 获取驾驶员累计扣分
     */
    @GetMapping("/sum-point-deduction/driver/{driverId}")
    public CommonResult<Integer> sumPointDeductionByDriver(@PathVariable Long driverId) {
        // 验证驾驶员是否存在
        // if (!driverService.exists(driverId)) {
        //     return CommonResult.failed("驾驶员不存在");
        // }
        
        Integer totalPoints = trafficViolationService.sumPointDeductionByDriverId(driverId);
        return CommonResult.success(totalPoints);
    }

    /**
     * 按月统计违章
     */
    @GetMapping("/statistics-by-month")
    public CommonResult<List<Map<String, Object>>> statisticsByMonth(@RequestParam(required = false) Integer year) {
        List<Map<String, Object>> statistics = trafficViolationService.statisticsByMonth(year);
        return CommonResult.success(statistics);
    }

    /**
     * 按违章类型统计
     */
    @GetMapping("/statistics-by-type")
    public CommonResult<List<Map<String, Object>>> statisticsByType() {
        List<Map<String, Object>> statistics = trafficViolationService.statisticsByViolationType();
        return CommonResult.success(statistics);
    }

    /**
     * 测试接口
     */
    @GetMapping("/test")
    public CommonResult<String> test() {
        return CommonResult.success("交通违章记录API正常工作");
    }
} 